package com.ysd.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ysd.entity.Admin;

//Filter 过滤器
public class LoginFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest)request;//强转
		HttpServletResponse res = (HttpServletResponse)response;
		
		HttpSession session = req.getSession();
		Admin admin = (Admin)session.getAttribute("admin");
		
		String url = req.getRequestURI();//获得访问的路径
		System.out.println(url.indexOf("login.html"));
		if (url.endsWith(".css") || url.endsWith(".js") || url.endsWith(".jpg")) {//访问静态资源放行
			chain.doFilter(req, res);//放行
		} else if(url.indexOf("login.html") > 0) {//代表访问的是登录页面
			chain.doFilter(req, res);//放行
		} else {//代表访问的不是登录页面
			if (admin != null) {
				chain.doFilter(req, res);//放行
			} else {
				res.sendRedirect("/shangcheng1/admin/login.html");//重定向
				//绝对路径: 前面有/ 会完全按照所写的路径去访问
				//相对路径: 前面没有/ 相对路径是相对于本文件的地址去访问
			}
		} 

	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
